<?php
class img_processor {
	/**
	 * Image file path
	 *
	 * @var string
	 */
	private $file_path;

	/**
	 * Constructor
	 *
	 * @param string $file_path
	 */
	public function __construct($file_path = "") {
		$this->set_file($file_path);
	}

	/**
	 * Sets file path to process
	 *
	 * @param string $file_path
	 */
	public function set_file($file_path = "") {
		$this->file_path = $file_path;
	}

	/**
	 * Renders image to screen
	 *
	 * @param int $new_width
	 * @param int $new_height
	 * @return bool
	 */
	public function render($new_width = null, $new_height = null) {
		$info = getimagesize($this->file_path);
		if ($info === false) return false;

		if ($new_width === null || $new_height === null) {
			$fp = fopen($this->file_path, "rb");
			header("Content-type: {$info['mime']}");
			fpassthru($fp);
			return true;
		} elseif (intval($new_width) > 0 && intval($new_height) > 0) {
			if ($new_width >= $info[0] && $new_height >= $info[1]) {
				return $this->render();
			}
			$result = $this->resize($new_width, $new_height);
			if ($result === false) return false;

			$source = imagecreatefromstring(file_get_contents($this->file_path));
			$thumb = imagecreatetruecolor($new_width, $new_height);
			imagecopyresized($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $info[0], $info[1]);
			imagepng($thumb);

			return true;
		}

		return false;
	}

	/**
	 * Gets new image width and height according to aspect ratio
	 *
	 * @param int $img_width
	 * @param int $img_height
	 * @return bool
	 */
	public function resize(&$img_width, &$img_height) {
		$result = getimagesize($this->file_path);
		if ($result === false) return false;

		list($img_w, $img_h) = array($result[0], $result[1]);

		if ($img_w <= $img_width && $img_h <= $img_height) return true;

		$ratio_w = $img_width / $img_w;
		$ratio_h = $img_height / $img_h;
		$ratio = min($ratio_w, $ratio_h);

		$img_width = intval($img_w * $ratio);
		$img_height = intval($img_h * $ratio);

		return true;
	}

	/**
	 * Renders blank image to screen
	 *
	 * @param int $img_width
	 * @param int $img_height
	 */
	public function blank_image($img_width = 128, $img_height = 128) {
		$img = imagecreatetruecolor($img_width, $img_height);

		$color_white = imagecolorallocate($img, 255, 255, 255);
		$color_gray = imagecolorallocate($img, 200, 200, 200);

		imagefill($img, 0, 0, $color_white);

		if ($width > 30 && $height > 20) {
			$x = round($img_width / 2 - 15);
			$y = round($img_height / 2 - 10);
			imagestring($img, 5, $x, $y, "N/A", $color_gray);
		}
		
		imagepng($img);
	}
}
?>